<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-11-02 14:52:55
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 * 中间变middle  连接 库存账MpcSummaryDetail  + 单据Model
 * 库存账MpcSummaryDetail  子表 库存批次账MpcBatchDetail
 * 库存批次账MpcBatchDetail 连接 批次库存MpcBacthStorage
 * 
 * 根据汇总库存查 账，--》批次库存--》批次库存账--》库存账
 */

namespace App\Repositories;

use App\Models\VmSummaryStorage;
use App\Models\MpcBacthStorage;
use App\Models\MpcSummaryStorage;
use App\Models\MpcBatchDetail;

use App\Models\MpcSummaryDetail;
use App\Models\MpcSummaryStorageBack;
use App\Models\Unit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * @property MpcBacthStorage $batch_model
 * @property MpcSummaryStorage $model
 * @property MpcBatchDetail $detail
 * @property MpcSummaryDetail $sum_detail
 * @property AutoCodeRepository $auto_code 自动编码
 * @property MpcSummaryStorageBack $mode_back 备份0数量库存
 * @property VmSummaryStorage $vm_storage
 */
class StorageRepository extends Repositories
    {
    public $isoutsoucing = false;
    public $whereFields = [
        'material_id' => ['key' => 'material_id'],
        'custno'      => ['key' => 'custno', 'default' => ''],
        'dyelot'      => ['key' => 'dyelot', 'default' => ''],
        'grade'       => ['key' => 'grade', 'default' => 'A'],
        'location_id' => ['key' => 'location_id'],
        'color_name'  => ['key' => 'color_name', 'default' => ''],
        'company_id'  => ['key' => 'company_id', 'default' => 0],
        'customer_id' => ['key' => 'customer_id', 'default' => 0],
        'iscustomer'  => ['key' => 'iscustomer', 'default' => 0],
        'batchno'     => ['key' => 'batchno'],
        'reel'        => ['key' => 'reel', 'default' => 0],
        'craft'       => ['key' => 'craft', 'default' => ''],
        'unit_id'     => ['key' => 'unit_id', 'default' => ''],
        'sample_data' => ['key' => 'sample_data', 'default' => ''],
        'orderno'     => ['key' => 'orderno', 'default' => ''],
        'style'       => ['key' => 'style', 'default' => '']
    ];
    public $whereSumFields = [
        'material_id' => ['key' => 'material_id'],
        'custno'      => ['key' => 'custno', 'default' => ''],
        'dyelot'      => ['key' => 'dyelot', 'default' => ''],
        'grade'       => ['key' => 'grade', 'default' => 'A'],
        'location_id' => ['key' => 'location_id'],
        'color_name'  => ['key' => 'color_name', 'default' => ''],
        'company_id'  => ['key' => 'company_id', 'default' => 0],
        'customer_id' => ['key' => 'customer_id', 'default' => 0],
        'iscustomer'  => ['key' => 'iscustomer', 'default' => 0],
        'batchno'     => ['key' => 'batchno'],
        'unit_id'     => ['key' => 'unit_id', 'default' => ''],
        'reel'        => ['key' => 'reel', 'default' => 0],
        'craft'       => ['key' => 'craft', 'default' => ''],
        'sample_data' => ['key' => 'sample_data', 'default' => ''],
        'orderno'     => ['key' => 'orderno', 'default' => ''],
        'style'       => ['key' => 'style', 'default' => '']
    ];
    public $sumFields = [
        'in_quantity',
        'in_auxiliary_quantity',
        'occupy_quantity',
        'occupy_auxiliary_quantity',
        'available_quantity',
        'available_auxiliary_quantity',
        'out_quantity',
        'out_auxiliary_quantity',
    ];
    protected $relation_models = ['location', 'material', 'company', 'customer', 'unit', 'type'];
    public function boot(
        MpcBacthStorage $batch_model,
        MpcSummaryStorage $model,
        MpcBatchDetail $detail,
        MpcSummaryDetail $sum_detail,
        AutoCodeRepository $auto_code,
        MpcSummaryStorageBack $mode_back,
        VmSummaryStorage $vm_storage
    ) {
        $this->batch_model = $batch_model;
        $this->model       = $model;
        $this->detail      = $detail;
        $this->sum_detail  = $sum_detail;
        $this->auto_code   = $auto_code;
        $this->mode_back   = $mode_back;
        $this->vm_storage  = $vm_storage;
        }
    public function setWhere($whereFields, $model)
        {
        $this->whereFields = $whereFields;
        return $model;
        }
    public function setOutSoucing($flag = true, $model)
        {
        $this->isoutsoucing = $flag;
        return $model;
        }
    public function getBatchStorage($data, $where = null)
        {
        $where = $this->getWhereData($data, $where);
        return $this->batch_model->where($where)
            ->where(function ($query)
                {
                $query->orWhere("available_quantity", ">", 0);
                $query->orWhere("occupy_quantity", ">", 0);
                })
            ->lockForUpdate()
            ->get();
        }
    public function getWhereData($model, $where = null) : array
        {
        $whereData = $this->whereFields;
        foreach ($where ?? $this->whereFields as $key => $value) {
            if (is_array($value)) {
                if (isset($model[$value['key']]))
                    $whereData[$key] = $model[$value['key']];
                else
                    if (isset($value['default'])) {
                        $whereData[$key] = $value['default'];
                        }
                    else if (isset($model[$key])) {
                        $whereData[$key] = $model[$key];
                        }
                    else {
                        fail("库存操作需要设置字段[{$key}]值！操作失败");
                        }
                }
            else
                $whereData[$key] = $value;

            }

        return $whereData;
        }
    public function mergeWhere($where)
        {

        $this->whereFields = array_merge($this->whereFields, $where);
        return $this;
        }

    private function setSumStorage($where)
        {
        //批次库存 
        $BatchList = $this->getBatchStorage($where, $this->whereSumFields);

        // dd($BatchList);
        //汇总库存
        $SumData = $this->getSumStorage($where);
        //计算合并
        $SumData = $this->computeSumStorage($SumData, $BatchList);

        $SumData->save();
        //虚拟视图库存还存在，就不清空，否则出入库明细查不到
        $vm_m = VmSummaryStorage::where("iscustomer", $SumData->iscustomer)
            ->where("batchno", $SumData->batchno)
            ->where("material_id", $SumData->material_id)
            ->where("unit_id", $SumData->unit_id)
            ->where("location_id", $SumData->location_id)
            ->where("dyelot", $SumData->dyelot)
            ->where("color_name", $SumData->color_name)
            ->where("grade", $SumData->grade)
            ->where(function ($query)
                {
                $query->orWhere("available_quantity", ">", 0);
                $query->orWhere("occupy_quantity", ">", 0);
                })
            ->first();
        //剩余库存大于0，保存

        if ($vm_m && $vm_m->available_quantity + $vm_m->occupy_quantity == 0) {
            //剩余库存等于小于0，创建备份，汇总库存删除
            $this->mode_back->create($SumData->toArray());
            $SumData->delete();
            }
        return $SumData;
        }
    private function getSumStorage($where)
        {
        $SumData      = $this->where($where)->first();
        $SumData_back = null;
        //未找到汇总库存
        if (isEmpty($SumData)) {
            //备份库存中查找
            $SumData_back = $this->mode_back->where($where)->first();
            //备份中也没有，就创建
            if (isEmpty($SumData_back)) {
                $SumData = $this->create($where);
                }
            else {
                //备份中有，根据备份创建一个汇总，删除备份
                $SumData = $this->create($SumData_back->toArray());
                $SumData_back->delete();
                }
            }
        return $SumData;
        }
    private function computeSumStorage($sum_model, $batch_model)
        {
        array_filter($this->sumFields, function ($v) use ($sum_model, $batch_model)
            {
            $sum_model->{$v} = array_sum(
                array_map(
                    function ($val) use ($v)
                        {
                        return $val[$v];
                        }
                    ,
                    $batch_model->toArray()
                )
            );
            });
        return $sum_model;
        }

    private function setUnit($model)
        {

        }
    /**
     * Summary of add
     * 建议在model中 use StorageTrait addStorage
     * @param Model $model 需要操作的模型
     * @param mixed $quantity 需要新增的数量
     * @param mixed $auxiliary_quantity 需要新增的辅助数量
     * @param mixed $name   出入库值
     * @param mixed $code   入库单号
     * @param mixed $middle_name 中间表保存ID的字段
     * @param mixed $sourcekey  数据源表的keyfield
     * @param mixed $targetkey  目标表的keyfield
     * @return MpcSummaryDetail
     */
    public function add(Model $model, $quantity = 0, $auxiliary_quantity = 0, $name = '', $code = '', $middle_name = "mpc_detail", $sourcekey = 'id')
        {
        $type_id          = $model->type_id ?? ($model->location->is_material == 1 ? 1 : 2);
        $where            = $this->getWhereData($model);
        $coefficient      = 1;
        $where['type_id'] = $type_id;
        if (isEmpty($where['unit_id'] ?? "")) {
            $where['unit_id'] = $model->material->uunit_id;
            if (isEmpty($where['unit_id'])) {
                fail("基础资料中[{$model->material->name}]库存单位未填写");
                }
            $coefficient = $this->getUnitCoefficient($model, $where['unit_id']);
            }
        $code = $code != '' ? $code : ($model->code ?? $model->getPaperCode());
        //根据自动编码的名字获取单据名字
        $name = $name != '' ? $name : $this->auto_code->whereKey($model->getACCode())->value("name");

        $sums                          = [];
        $sums['in_quantity']           = $sums['available_quantity'] = ($quantity == 0 ? $model->quantity : $quantity) * $coefficient;
        $sums['in_auxiliary_quantity'] =
            $sums['available_auxiliary_quantity'] =
            $auxiliary_quantity == 0 ?
            ($model->auxiliary_quantity ?? 0) : $auxiliary_quantity;
        if ($sums['in_quantity'] == 0) {
            fail("入库数量不能小于等于0！");
            }
        //保存批次库存
        $BatchStorageData = array_merge($where, ['code' => $code], $model->getStorageMergeData());
        //汇总库存账
        $sumDetail = $this->sum_detail->create([
            'name'                  => $name,
            'code'                  => $code,
            'in_quantity'           => $sums['in_quantity'],
            'in_auxiliary_quantity' => $sums['in_auxiliary_quantity'],
            'source_model'          => $model::class,
            'source_key'            => $sourcekey,
            'source_value'          => $model->{$sourcekey},
            'material_id'           => $BatchStorageData['material_id'],
            'dyelot'                => $BatchStorageData['dyelot'],
            'color_name'            => $BatchStorageData['color_name'],
            'location_id'           => $BatchStorageData['location_id'],
            'type_id'               => $type_id,
            'company_id'            => $BatchStorageData['company_id'],
            'batchno'               => $BatchStorageData['batchno'],
            'iscustomer'            => $BatchStorageData['iscustomer'],
            'summary_storage_id'    => 0
        ]);

        $modelBatch = $model->getBatchStorage();
        if ($modelBatch == null) {
            $BatchData = $this->batch_model->create(array_merge($BatchStorageData, $sums));
            $this->detail->create([
                'in_quantity'           => $sums['in_quantity'],
                'in_auxiliary_quantity' => $sums['in_auxiliary_quantity'],
                'batch_storage_id'      => $BatchData->id,
                'summary_detail_id'     => $sumDetail->id,
            ]);
            }
        else {
            $modelBatch->filter(function ($v) use ($BatchStorageData, $sumDetail)
                {
                $BatchStorageData['available_quantity']           = $BatchStorageData['in_quantity'] = $v->quantity;
                $BatchStorageData['available_auxiliary_quantity'] = $BatchStorageData['in_auxiliary_quantity'] = $v->auxiliary_quantity;

                $BatchData = $this->batch_model->create($BatchStorageData);
                $this->detail->create([
                    'in_quantity'           => $BatchStorageData['in_quantity'],
                    'in_auxiliary_quantity' => $BatchStorageData['in_auxiliary_quantity'],
                    'batch_storage_id'      => $BatchData->id,
                    'summary_detail_id'     => $sumDetail->id,
                ]);
                });
            }
        //创建库存的单据
        $model->{$middle_name . "_id"} = $sumDetail->id;
        $model->save();


        //计算汇总库存
        $sumDetail->summary_storage_id = $this->setSumStorage($where)->id;
        $sumDetail->save();
        return $sumDetail;
        }

    public function use(
        Model $model,
        $quantity = 0,
        $auxiliary_quantity = 0,
        $saveMiddleIdFieldName = "mpc_detail",
        $name = '',
        $code = '',
        $sourcekey = 'id',
    ) {
        $where = $this->getWhereData($model);

        if (isEmpty($where['unit_id'] ?? "")) {
            $where['unit_id'] = $model->material->uunit_id;
            if (isEmpty($where['unit_id']))
                fail("基础资料中[{$model->material->name}]库存单位未填写");
            }
        //获取扣库转换率
        $coefficient = $this->getUnitCoefficient($model, $where['unit_id']);
        //根据自动编码的名字获取单据名字
        $name = $name != '' ? $name : $this->auto_code->whereKey($model->getACCode())->value("name");
        $code = $code != '' ? $code : ($model->code ?? $model->getPaperCode());

        $BatchDatas = $model->getBatchStorage();
        if ($BatchDatas && $BatchDatas->count() > 0) {
            $fisrtStorage       = $BatchDatas[0];
            $quantity           = ($quantity ?? $model->quantity ?? 0) * $coefficient;
            $mpc_batch          = $fisrtStorage->mpc_batch;
            $auxiliary_quantity = ($auxiliary_quantity ?? $model->auxiliary_quantity ?? ($mpc_batch['in_auxiliary_quantity']) / $mpc_batch['in_quantity'] * $quantity);

            //循环扣库存
            $whereSumFieldsData = $this->autoUserBatchStorage($BatchDatas, $quantity, $auxiliary_quantity, $name, $code, $model, $sourcekey);

            }
        else {
            $BatchDatas = $this->where("available_quantity", ">", 0)->getBatchStorage($where);

            if ($BatchDatas && $BatchDatas->count() > 0) {
                $fisrtStorage       = $BatchDatas[0];
                $quantity           = ($quantity ?? $model->quantity ?? 0) * $coefficient;
                $auxiliary_quantity = ($auxiliary_quantity ?? $model->auxiliary_quantity ?? ($fisrtStorage['in_auxiliary_quantity']) / $fisrtStorage['in_quantity'] * $quantity);
                //循环扣库存
                $whereSumFieldsData = $this->autoUserCustomerSotage($BatchDatas, $quantity, $auxiliary_quantity, $name, $code, $model, $sourcekey);
                }
            else {
                // 替换绑定  
                fail("库存不足！占用库存失败！流转批号：" . ($where['batchno'] ?? "") . ",物料:" . $model->material->name);
                }
            }


        foreach ($whereSumFieldsData as $value) {
            $sumDetail                               = $value['model'];
            $model->{$saveMiddleIdFieldName . "_id"} = $sumDetail->main_id;
            $sumDetail->summary_storage_id           = $this->setSumStorage($value['where'])->id;
            $sumDetail->save();
            }

        $model->save();
        return $model->refresh();
        }
    private function getUnitCoefficient($model, $unit_id)
        {
        $coefficient    = 1;
        $model->unit_id = $model->unit_id ?? $unit_id;
        if ($unit_id != $model->unit_id) {
            $coefficient = $model->material?->coefficient ?? 1;
            }
        return $coefficient;
        }
    public function createUseSumDetails($fisrtStorage, $sourcekey, $model, $code, $name, $quantity, $auxiliary_quantity)
        {
        return $this->sum_detail->create([
            'name'                      => $name,
            'code'                      => $code,
            'occupy_quantity'           => $quantity,
            'occupy_auxiliary_quantity' => $auxiliary_quantity,
            'source_model'              => $model::class,
            'source_key'                => $sourcekey,
            'source_value'              => $model->{$sourcekey},
            'material_id'               => $fisrtStorage['material_id'],
            'dyelot'                    => $fisrtStorage['dyelot'],
            'color_name'                => $fisrtStorage['color_name'],
            'location_id'               => $fisrtStorage['location_id'],
            'company_id'                => $fisrtStorage['company_id'],
            'batchno'                   => $fisrtStorage['batchno'],
            'iscustomer'                => $fisrtStorage['iscustomer'],
            'summary_storage_id'        => 0
        ]);
        }
    //创建明细
    private function createUseDetails($BatchData, $sumDetail_id, $quantity, $auxiliary_quantity)
        {
        //创建明细账
        $this->detail->create([
            'occupy_quantity'           => $quantity,
            'occupy_auxiliary_quantity' => $auxiliary_quantity,
            'batch_storage_id'          => $BatchData->id,
            'summary_detail_id'         => $sumDetail_id,
        ]);
        //增加占用
        $BatchData->occupy_quantity += $quantity;
        $BatchData->occupy_auxiliary_quantity += $auxiliary_quantity;

        //减少可用
        $BatchData->available_quantity -= $quantity;
        $BatchData->available_auxiliary_quantity -= $auxiliary_quantity;

        $BatchData->save();
        }
    private function autoUserCustomerSotage($BatchDatas, $quantity, $auxiliary_quantity, $name, $code, $model, $sourcekey)
        {
        $whereSumFieldsData = [];
        $main_id            = 0;
        foreach ($BatchDatas as $BatchData) {
            if ($quantity <= 0)
                break;
            $whereSum = $this->getWhereData($BatchData, $this->whereSumFields);
            $sumkey   = implode("_", $whereSum);

            if (!isset($whereSumFieldsData[$sumkey])) {
                $sumDetail                            = $this->createUseSumDetails($BatchData, $sourcekey, $model, $code, $name, $quantity, $auxiliary_quantity);
                $whereSumFieldsData[$sumkey]['model'] = $sumDetail;
                $whereSumFieldsData[$sumkey]['where'] = $whereSum;
                if ($main_id == 0) {
                    $main_id = $sumDetail->id;
                    }
                $sumDetail->main_id = $main_id;
                }
            else {
                $sumDetail = $whereSumFieldsData[$sumkey]['model'];
                }
            if ($BatchData->available_quantity <= $quantity) {
                //创建明细账  
                $quantity -= $BatchData->available_quantity;
                $auxiliary_quantity -= $BatchData->available_auxiliary_quantity;
                $this->createUseDetails($BatchData, $sumDetail->id, $BatchData->available_quantity, $BatchData->available_auxiliary_quantity);
                }
            else {
                if ($quantity != 0) {
                    //创建明细账
                    $this->createUseDetails($BatchData, $sumDetail->id, $quantity, $auxiliary_quantity);
                    $quantity = 0;
                    }
                }
            }
        if ($quantity > 0)
            fail("数量不足！");
        return $whereSumFieldsData;
        }
    private function autoUserBatchStorage($BatchDatas, $quantity, $auxiliary_quantity, $name, $code, $model, $sourcekey)
        {

        $whereSumFieldsData = [];
        $main_id            = 0;
        foreach ($BatchDatas as $BatchData) {
            $whereSum = $this->getWhereData($BatchData, $this->whereSumFields);
            $sumkey   = implode("_", $whereSum);

            if (!isset($whereSumFieldsData[$sumkey])) {
                $sumDetail                            = $this->createUseSumDetails($BatchData, $sourcekey, $model, $code, $name, $quantity, $auxiliary_quantity);
                $whereSumFieldsData[$sumkey]['model'] = $sumDetail;
                $whereSumFieldsData[$sumkey]['where'] = $whereSum;
                if ($main_id == 0) {
                    $main_id = $sumDetail->id;
                    }
                $sumDetail->main_id = $main_id;
                }
            else {
                $sumDetail = $whereSumFieldsData[$sumkey]['model'];
                }
            if ($BatchData->quantity <= $quantity) {
                //创建明细账  
                $quantity -= $BatchData->quantity;
                $auxiliary_quantity -= $BatchData->available_auxiliary_quantity;
                $this->createUseDetails($BatchData->mpc_batch, $sumDetail->id, $BatchData->quantity, $BatchData->auxiliary_quantity);
                }
            else {
                if ($quantity != 0) {
                    //创建明细账
                    $this->createUseDetails($BatchData->mpc_batch, $sumDetail->id, $quantity, $auxiliary_quantity);
                    $quantity = 0;
                    }
                }
            }
        if ($quantity > 0)
            fail("数量不足！");
        return $whereSumFieldsData;
        }
    public function sub(Model $model, $saveMiddleRelationName = "mpc_detail")
        {

        $sumDetail_m = $model->{$saveMiddleRelationName};
        $sumDetails  = $sumDetail_m->maindetails;
        foreach ($sumDetails as $sumDetail) {
            if ($sumDetail->occupy_quantity <= 0) {
                fail("无法出库！没有占用库存！");
                }
            $details = $sumDetail->details;
            foreach ($details as $detail) {
                $batchData = $detail->batch_storage;
                if ($detail->occupy_quantity <= 0) {
                    fail("出库失败！占用数量是0，无法出库！");
                    }
                $batchData->occupy_quantity -= $detail->occupy_quantity;
                $batchData->occupy_auxiliary_quantity -= $detail->occupy_auxiliary_quantity;
                $batchData->out_quantity += $detail->occupy_quantity;
                $batchData->out_auxiliary_quantity += $detail->occupy_auxiliary_quantity;

                $detail->out_quantity              = $detail->occupy_quantity;
                $detail->out_auxiliary_quantity    = $detail->occupy_auxiliary_quantity;
                $detail->occupy_quantity           = 0;
                $detail->occupy_auxiliary_quantity = 0;
                $batchData->save();
                $detail->save();
                }
            $sumDetail->out_quantity              = $sumDetail->occupy_quantity;
            $sumDetail->out_auxiliary_quantity    = $sumDetail->occupy_auxiliary_quantity;
            $sumDetail->occupy_quantity           = 0;
            $sumDetail->occupy_auxiliary_quantity = 0;
            $sumDetail->save();
            //设置总库
            $where = $this->getWhereData($details[0]->batch_storage, $this->whereSumFields);
            $this->setSumStorage($where);
            }
        return $model;
        }

    public function noadd(Model $model, $middle_name = 'mpc_detail')
        {
        $sumDetail          = $model->{$middle_name};
        $details            = $sumDetail->details;
        $where              = $this->getWhereData($details[0]->batch_storage);
        $available_quantity = 0;

        foreach ($details as $detail) {
            $batchData          = $detail->batch_storage;
            $available_quantity += $batchData->available_quantity;
            $batchData->delete();
            $detail->delete();
            }
        if ($available_quantity < $sumDetail->in_quantity) {
            fail('库存不足！已被使用！');
            }
        $sumDetail->delete();


        $model->{$middle_name . "_id"} = 0;
        $model->save();
        $this->setSumStorage($where);
        return $model->refresh();
        }
    public function nouse(Model $model, $saveMiddleRelationName = "mpc_detail")
        {
        $sumDetail_m = $model->{$saveMiddleRelationName};
        $sumDetails  = $sumDetail_m->maindetails;
        foreach ($sumDetails as $sumDetail) {
            $details = $sumDetail->details;
            $where   = $this->getWhereData($details[0]->batch_storage, $this->whereSumFields);

            foreach ($details as $detail) {
                if ($detail->occupy_quantity <= 0) {
                    fail("取消占用库存失败！占用数量是0，无法取消占用！");
                    }
                $batchData                               = $detail->batch_storage;
                $batchData->occupy_quantity -= $detail->occupy_quantity;
                $batchData->occupy_auxiliary_quantity -= $detail->occupy_auxiliary_quantity;
                $batchData->available_quantity += $detail->occupy_quantity;
                $batchData->available_auxiliary_quantity += $detail->occupy_auxiliary_quantity;
                $detail->delete();
                $batchData->save();
                }
            $sumDetail->delete();
            $this->setSumStorage($where);
            }
        $model->{$saveMiddleRelationName . "_id"} = 0;
        $model->save();


        return $model->refresh();
        }
    public function nosub(Model $model, $saveMiddleRelationName = "mpc_detail")
        {
        $sumDetail_m = $model->{$saveMiddleRelationName};
        $sumDetails  = $sumDetail_m->maindetails;
        foreach ($sumDetails as $sumDetail) {

            $details = $sumDetail->details;

            foreach ($details as $detail) {

                $batchData = $detail->batch_storage;
                if ($detail->out_quantity <= 0) {
                    fail("取消出库失败！出库数量是0，无法取消出库！");
                    }
                $batchData->occupy_quantity += $detail->out_quantity;
                $batchData->occupy_auxiliary_quantity += $detail->out_auxiliary_quantity;
                $batchData->out_quantity -= $detail->out_quantity;
                $batchData->out_auxiliary_quantity -= $detail->out_auxiliary_quantity;
                $batchData->save();
                $detail->occupy_quantity += $detail->out_quantity;
                $detail->occupy_auxiliary_quantity += $detail->out_auxiliary_quantity;
                $detail->out_quantity              = 0;
                $detail->out_auxiliary_quantity    = 0;
                $detail->save();
                }
            $sumDetail->occupy_quantity += $sumDetail->out_quantity;
            $sumDetail->occupy_auxiliary_quantity += $sumDetail->out_auxiliary_quantity;
            $sumDetail->out_quantity              = 0;
            $sumDetail->out_auxiliary_quantity    = 0;
            $sumDetail->save();
            $where = $this->getWhereData($sumDetail->details[0]->batch_storage, $this->whereSumFields);
            $this->setSumStorage($where);
            }
        return $model;
        }
    }